<?php
/**
 * 商品云组件Model
 * @file 	ItemsModel.class.php
 * @author 	kelecode@gmail.com
 * @date 	2013-06-15
 * modify
 */
class ItemsModel extends Model{

	private $table;
	public $pageSize;

	public function __construct(){
		parent::__construct();

		$this->table = C('db_table_prefix').'items';
		$this->pageSize = C('page.page_size');
	}

	/**
	 * 获取指定分类的商品列表
	 * @param int $cid
	 * @return array $items
	 */
	public function getItemsByCid($cid){
		if(empty($cid)){
			return array();
		}
		$categories = array();
		$sql = "SELECT `id`,`cid`,`name`,`url`,`image`,`description`
				FROM `{$this->table}`
				WHERE `status`=1 AND `cid`='{$cid}'
				ORDER BY `sort` ASC, `id` DESC";
		$items = $this->query($sql);

		return $items;
	}

	/**
	 * 获取单条或全部商品列表
	 * @param int $id
	 * @return array $lists
	 */
	public function itemList($id=null){
		$pageSize = $this->pageSize;
		$currentPage = (int)$_GET[C('page.var_page')];
		$currentPage = $currentPage <= 0 ? 1 : $currentPage;
		$start = ($currentPage - 1) * $pageSize;
        $start = $start < 0 ? 0 : $start;

		$lists = array();
		$sql = "SELECT count(*) AS count FROM `{$this->table}` WHERE `status`=1";
		if($id){
			$sql .= " AND `id`='{$id}'";
		}
		$count = $this->query($sql);
        $count = $count[0]['count'];
        $sql = str_replace('count(*) AS count','*',$sql);
        $sql .= " ORDER BY `sort` ASC, `id` DESC LIMIT {$start},{$pageSize}";
		$lists = $this->query($sql);

		return array('count' => $count,'lists' => $lists);
	}

	/**
	 * 获取单条商品数据
	 */
	public function getItemById($id){
		if(empty($id)){
			return false;
		}
		$items = $this->itemList($id);

		return $items['lists'][0];
	}

	/**
	 * 获取所有商品数据
	 */
	public function getItems(){
		$categoriesTable = C('db_table_prefix').'categories';
		$sql = "SELECT A.*,B.name AS `cat_name`,B.`order`
				FROM `{$this->table}` A LEFT JOIN `{$categoriesTable}` B ON A.`cid`=B.id
				WHERE A.`status`='1' AND B.`status`='1'
				ORDER BY B.`order` ASC,B.`id` ASC;";
		$result = $this->query($sql);
		$items = array();
		if( ! empty($result)){
			foreach($result as $val){
				$items[$val['cid']][] = $val;
			}
		}

		return $items;
	}

	/**
	 * 添加商品
	 */
	public function addItem($data){
		if( empty($data) || !is_array($data)){
			return false;
		}
		foreach($data as $k => $v){
			$data[$k] = mysql_escape_string($v);
		}
		extract($data);
		$time = time();
		$sql = "INSERT INTO `{$this->table}`
					(`cid`, `name`, `price`, `url`, `seller_name`, `seller_url`, `image`, `brokerage`, `more_info`, `description`,`ctime`,`utime`)
					VALUES ('{$cid}', '{$name}', '{$price}', '{$url}', '{$seller_name}', '{$seller_url}', '{$image}', '{$brokerage}', '{$more_info}', '{$description}', '{$time}', '{$time}')";
		$result = $this->execute($sql);

		return $result;
	}

	/**
	 * 编辑商品
	 * @param array $data
	 * @return boolean true or false
	 */
	public function editItem($data){
		if( empty($data) || !is_array($data)){
			return false;
		}
		foreach($data as $k => $v){
			$data[$k] = mysql_escape_string($v);
		}
		extract($data);
		$utime = time();
		$sql = "UPDATE `{$this->table}` SET 
					`cid`='{$cid}', `name`='{$name}', `price`='{$price}', `url`='{$url}', `seller_name`='{$seller_name}', `seller_url`='{$seller_url}', `image`='{$image}', `brokerage`='{$brokerage}', `more_info`='{$more_info}', `description`='{$description}', `utime`='{$utime}'
					WHERE `id`='{$id}'";
		$result = $this->execute($sql);
		
		return $result;
	}

	/**
	 * 删除商品
	 * @param int $id
	 * @return boolean true or false
	 */
	public function delItem($ids){
		if(empty($ids)){
			return false;
		}
		if(is_array($ids)){
			$id = implode(',',$ids);
		}else{
			$id = (int)$ids;
		}
		$sql = "UPDATE `{$this->table}` SET `status`='0' WHERE `id` in ({$id})";
		$result = $this->execute($sql);

		return $result;
	}

	public function saveCsvData($datas){
		$time = time();
		$sql = "INSERT INTO `{$this->table}`
			(`cid`, `name`, `price`, `url`, `seller_name`, `seller_url`, `image`, `brokerage`, `more_info`, `description`,`sort`,`ctime`,`utime`,`status`) VALUES ";
			foreach($datas as $key => $data){
				$cid = (int)$data['cid'];
				$name = mysql_escape_string( iconv('gbk','utf-8',$data['name']) );
				$price = $data['price'];
				$url = mysql_escape_string($data['url']);
				$seller_name = mysql_escape_string( iconv('gbk','utf-8',$data['seller_name']) );
				$seller_url = mysql_escape_string($data['seller_url']);
				$image = mysql_escape_string($data['image']);
				$brokerage = mysql_escape_string($data['brokerage']);
				$more_info = mysql_escape_string($data['more_info']);
				$description = mysql_escape_string( iconv('gbk','utf-8',$data['description']) );
				$sort = (int)$data['sort'];
				$sort = $sort < 0 ? 9999 : $sort;
				$ctime = $data['ctime'];
				$utime = $data['utime'];
				$status = (int)$data['status'];
				$status = !in_array($status,array(0,1)) ? 0 : $status;

				$sql .= "('{$cid}', '{$name}', '{$price}', '{$url}', '{$seller_name}', '{$seller_url}', '{$image}', '{$brokerage}', '{$more_info}', '{$description}', '{$sort}', '{$ctime}', '{$utime}', '{$status}')";

				if( ($key +1) < count($datas)){
					$sql .= ', ';
				}
			}
		$result = $this->execute($sql);

		return $result;
	}

}